package com.xzx;

import jakarta.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/9/5 17:01
 */
public class ConsumerFromQueueListener {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            connection = getConnection();
            Session session = connection.createSession();

            Queue queue = session.createQueue("xzx");

            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(message -> {
                TextMessage msg = (TextMessage) message;
                System.out.println(msg);
            });
            // 本意让程序阻塞在这里不要
            System.in.read();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(connection);
        }
    }


    public static Connection getConnection() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
        try {
            Connection connection = activeMQConnectionFactory.createConnection();
            connection.start();
            return connection;
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    public static void closeConnection(Connection connection) {
        if (connection == null) {
            return;
        }

        try {
            connection.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

}
